package com.shan.tools.starter.datasource;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.Resource;
import javax.sql.DataSource;

@Configuration
@EnableConfigurationProperties(DataSourceProperties.class)
@EnableTransactionManagement
@MapperScan("com.shan.**.mapper")
public class DBAutoConfiguration {
    // TODO????? 这里扫描路径后续改为动态配置，以方便第三方使用

    @Resource
    private DataSourceProperties dataSourceProperties;
    
    public SqlSessionTemplate getSqlSession()
        throws Exception {
        return new SqlSessionTemplate(sqlSessionFactoryBean().getObject());
    }
    
    @Bean
    @Scope("prototype")
    SqlSessionTemplate sqlSessionTemplate()
        throws Exception {
        return this.getSqlSession();
    }
    
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean()
        throws Exception {
        SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(dataSource());
        PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver();
        /** 添加mapper 扫描路径 */
        // TODO????? mapper扫描classPath路径后续改为可配置 先期定制化
        String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + "com/shan/**/mapper/**/*Mapper.xml";
        sqlSessionFactory.setMapperLocations(pathMatchingResourcePatternResolver.getResources(packageSearchPath));
        return sqlSessionFactory;
    }
    
    @Bean
    DataSource dataSource() {
        return DBHelper.buildDataSource(dataSourceProperties);
    }
    
    @Bean DataSourceTransactionManager dataSourceTransactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }
}
